﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Data.Common;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace Gaea
{
    using SuperPower;
    public partial class DefaultGaeaConnectionFactory : IGaeaConnectionFactory
    {
        private static IServiceProvider _container;
        private static string _connectionStringConfigureName;
        private static Func<DbConnection> _dbConnectionFactoryCore;
        private static Dictionary<string, string> _connectionStringCache;

        public static void Register(IServiceProvider container, string connectionString, string nameSymbo = "", bool enableGaeaSuperName = true, Func<DbConnection> dbConnectionFactoryCore = null)
        {
            _container = container;
            _connectionStringCache = new Dictionary<string, string>();
            _connectionStringCache.Add("", connectionString);
            GaeaSuperPower.InitNameSymbol(nameSymbo);
            if (enableGaeaSuperName)
            {
                GaeaSuperPower.EnableGaeaSuperName();
            }
            _dbConnectionFactoryCore = dbConnectionFactoryCore;
        }

        public virtual async Task<DbConnection> GetConnectionAsync()
        {
            if (_dbConnectionFactoryCore != null)
            {
                return _dbConnectionFactoryCore();
            }
            if (_container == null)
            {
                throw new Exception("PLEASE RESIGER FACTORY FIRST!");
            }

            var dbConnection = _container.GetRequiredService<DbConnection>();
            dbConnection.ConnectionString = _connectionStringCache[""];
            await dbConnection.OpenAsync();
            return dbConnection;
        }
    }
}
